﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Net;

namespace OutlookInvitationTest1
{
    public partial class SendOutlookInvitation2 : System.Web.UI.Page
    {
        DateTime timeNow;
        protected void Page_Load(object sender, EventArgs e)
        {
            timeNow = System.DateTime.Now;
            timeNow.AddMinutes(30);
            TextBox1.Text = timeNow.ToString();
        }


        protected void Button1_Click(object sender, EventArgs e)
        {
            OutlookMeetingGenerator outlookInitiativeGenerator = new OutlookMeetingGenerator();
            string invitationString = outlookInitiativeGenerator.buildMeetingRequest(timeNow, timeNow.AddMinutes(30), TextTargetName.Text, TextTargetEmail.Text, TextSenderEmail.Text, TextSubject.Text, TextDescription.Text, TextLocation.Text);
            sendICalendarInvitationEmail(invitationString, TextSenderEmail.Text, TextSenderPassword.Text, TextTargetEmail.Text);
        }

        protected void sendICalendarInvitationEmail(string invitationString, string senderAddress, string senderPassword, string recieverAddress)
        {
            //create calendar meeting request
            String meetingInfo = invitationString;
            System.Net.Mime.ContentType mimeType = new System.Net.Mime.ContentType("text/calendar; method=REQUEST");
            AlternateView ICSview = AlternateView.CreateAlternateViewFromString(meetingInfo, mimeType);

            var fromAddress = new MailAddress(senderAddress, "From " + senderAddress);
            var toAddress = new MailAddress(recieverAddress, "To " + recieverAddress);
            string fromPassword = senderPassword;

            //create email message with alternative view containing callendar request
            MailMessage message = new MailMessage(fromAddress, toAddress);
            message.AlternateViews.Add(ICSview);

            //connect to gmail smtp sever
            var smtp = new SmtpClient
            {
                Host = "smtp.gmail.com",
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
            };

            //send the message
            try
            {
                smtp.Send(message);
                Label1.Text = "Wiasomosc wyslana pomyslnie! do: " + recieverAddress;
            }
            catch (Exception ex)
            {
                Label1.Text = ex.ToString();
            }

        }
    }
}